﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;
using System.Web.Security;
using SmartProject.BusinessObjects;

namespace SmartProject.AppSpace
{
    public partial class Users : UI.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.SetPage("Users", "Manage user accounts");
                User user = new User();
                this.DrpRoles.DataSource = user.RoleNames;
                this.DrpRoles.DataBind();
                RefreshView(user);
            }
        }

        private void RefreshView(User user)
        {
            if (UI.BasePage.IsFirstTimePreferenceSetup)
            {
                Response.Redirect("~/AppSpace/Setup.aspx", true);
            }
            else
            {
                if (UI.BasePage.IsFirstTimeUserSetup)
                {
                    this.DrpRoles.SelectedValue = "Administrator";
                    this.DrpRoles.Enabled = false;
                    this.BtnCancel.Visible = false;
                    this.PopUser.Show();
                }
                else
                {
                    this.GrvUsers.DataSource = user.LoadUsers();
                    this.GrvUsers.DataBind();
                }
                
                BusinessRule businessRule = user.GetSelectedBusinessRule("UserName");
                if (businessRule != null)
                {
                    bool visible = businessRule.QueryBooleanProperty("IsEnableUserNameTextBox");
                    if (!visible)
                    {
                        this.TxtUserName.Visible = businessRule.QueryBooleanProperty("IsEnableUserNameTextBox");
                        this.LblUserNameExplain.InnerText = "Username is entered by the system based on your business rule preference.";
                    }
                    else
                    {
                        this.LblUserNameExplain.Visible = false;
                    }
                }
                else
                {
                    this.LblUserNameExplain.Visible = false;
                }
            }
        }

        protected void GrvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            SmartProject.BusinessObjects.User user = new SmartProject.BusinessObjects.User();
            HtmlInputHidden plcUserId = (HtmlInputHidden)this.GrvUsers.Rows[
                Convert.ToInt32(e.CommandArgument)].Cells[0].FindControl("PlcUserId");
            int userId = Convert.ToInt32(plcUserId.Value);
            switch (e.CommandName)
            {
                case "Edit":

                    user.SetAttribute("UserId", userId);
                    user.Load();
                    this.BtnSave.CommandArgument = plcUserId.Value;

                    string userName = (string)user.GetAttributeValue("Username");
                    this.TxtUserName.Text = userName;
                    this.PlcUserName.Value = this.TxtUserName.Text;

                    this.TxtFirstName.Text = (string)user.GetAttributeValue("FirstName");
                    this.PlcFirstName.Value = this.TxtFirstName.Text;

                    this.TxtLastName.Text = (string)user.GetAttributeValue("LastName");
                    this.PlcLastName.Value = this.TxtLastName.Text;

                    this.TxtEMail.Text = (string)user.GetAttributeValue("EMail");
                    this.PlcEMail.Value = this.TxtEMail.Text;

                    string role = Roles.GetRolesForUser(userName)[0];

                    int selectedIndex = -1;
                    for (int i = 0; i < this.DrpRoles.Items.Count; i++)
                    {
                        if (this.DrpRoles.Items[i].Value == role)
                        {
                            selectedIndex = i;
                            break;
                        }
                    }

                    this.DrpRoles.SelectedIndex = selectedIndex;

                    PopUser.Show();
                    break;

                case "Remove":

                    HtmlInputHidden plcUserName = (HtmlInputHidden)this.GrvUsers.Rows[
                        Convert.ToInt32(e.CommandArgument)].Cells[0].FindControl("PlcUserName");
                    try
                    {
                        user.SetAttribute("UserName", plcUserName.Value);
                        user.AddBusinessRuleParameter("UserId", userId);
                        user.AddBusinessRuleParameter("LoggedInUserId", base.UserId);
                        user.Remove();
                    }
                    catch (Exceptions.BusinessRuleViolation businessRuleViolation)
                    {
                        this.DisplayErrorOrWarning(businessRuleViolation.Message);
                        return;
                    }

                    RefreshView(user);
                    break;
            }
        }

        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            this.BtnSave.CommandArgument = String.Empty;
            this.TxtFirstName.Text = String.Empty;
            this.TxtLastName.Text = String.Empty;
            this.TxtUserName.Text = String.Empty;
            this.TxtPassword.Text = String.Empty;
            this.TxtVerifyPassword.Text = String.Empty;
            this.TxtEMail.Text = String.Empty;
            this.DrpRoles.SelectedIndex = 0;
            this.PopUser.Hide();
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            this.LblErrorMessage.Visible = false;

            // Password match validation.
            if (!String.IsNullOrEmpty(this.TxtPassword.Text))
            {
                if (this.TxtPassword.Text != this.TxtVerifyPassword.Text)
                {
                    this.LblErrorMessage.Visible = true;
                    this.LblErrorMessage.Text = "Passwords do not match!";
                    this.PopUser.Show();
                    return;
                }
            }

            User user = new User();
            try
            {
                user.SetAttribute("FirstName", this.TxtFirstName.Text);
                user.SetAttribute("LastName", this.TxtLastName.Text);
                user.SetAttribute("EMail", this.TxtEMail.Text);
            }
            catch (Exceptions.RequiredDataParameter requiredDataParameter)
            {
                LblErrorMessage.Visible = true;
                string fieldFriendlyName = String.Empty;
                switch (requiredDataParameter.AttributeName)
                {
                    case "FirstName":
                        fieldFriendlyName = "First Name";
                        break;

                    case "LastName":
                        fieldFriendlyName = "Last Name";
                        break;

                    case "EMail":
                        fieldFriendlyName = "E-Mail addresss";
                        break;
                }

                LblErrorMessage.Text = String.Format("{0} is a required field.", fieldFriendlyName);
                this.PopUser.Show();
                return;
            }

            // Username field is NOT validated.
            user.SetAttribute("UserName", this.TxtUserName.Text, false);
            user.AddBusinessRuleParameter("Password", this.TxtPassword.Text);
            user.AddBusinessRuleParameter("Role", this.DrpRoles.SelectedItem.Value);
            if (String.IsNullOrEmpty(this.BtnSave.CommandArgument))
            {
                bool isFirstTimeUserSetup = UI.BasePage.IsFirstTimeUserSetup;
                string temporaryUser = String.Empty;

                if (isFirstTimeUserSetup)
                {
                    user.AddBusinessRuleParameter("TemporaryUserName", User.Identity.Name);
                }

                // We are adding a new user.
                try
                {
                    user.Save();
                }
                catch (Exceptions.BusinessRuleViolation businessRuleViolation)
                {
                    this.LblErrorMessage.Visible = true;
                    this.LblErrorMessage.Text = businessRuleViolation.Message;
                    this.PopUser.Show();
                    return;
                }

                if (isFirstTimeUserSetup)
                {
                    FormsAuthentication.SignOut();
                    Response.Redirect("~/Default.aspx", true);
                }
            }
            else
            {
                // We are updating an existing user.
                user.SetAttribute("UserId", Convert.ToInt32(this.BtnSave.CommandArgument));
                user.AddBusinessRuleParameter("FirstName", this.PlcFirstName.Value);
                user.AddBusinessRuleParameter("LastName", this.PlcLastName.Value);
                user.AddBusinessRuleParameter("EMail", this.PlcEMail.Value);
                user.AddBusinessRuleParameter("UserName", this.PlcUserName.Value);
                user.AddBusinessRuleParameter("Password", this.TxtPassword.Text);
                try
                {
                    user.Update();
                }
                catch (Exceptions.BusinessRuleViolation businessRuleViolation)
                {
                    this.LblErrorMessage.Visible = true;
                    this.LblErrorMessage.Text = businessRuleViolation.Message;
                    this.PopUser.Show();
                    return;
                }
            }
            RefreshView(user);
        }

        protected void GrvUsers_RowEditing(object sender, GridViewEditEventArgs e)
        {
            // Do nothing. Required by GridView
        }

        public override void RefreshPage(object obj)
        {
            // Do nothing.
        }

        public override AjaxControlToolkit.ModalPopupExtender Popup(string name)
        {
            return null;
        }
    }
}
